package com.sd.projectinterface;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;

import objects.CSProb;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyAssignments extends Activity{
	
	TextView test;
	Button back;
	int id;
	public static final String KEY_121 = "http://10.0.2.2/mathRomp/getCurrentAssignments.php";
	public static final String KEY_122 = "http://10.0.2.2/mathRomp/getAssignmentProb.php";
	public static final String KEY_123 = "http://10.0.2.2/mathRomp/setAssignmentProblems.php";
	public static final String KEY_124 = "http://10.0.2.2/mathRomp/getCompletedAssignments.php";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_assignments);
		back = (Button) findViewById(R.id.back);
		test = (TextView) findViewById(R.id.test);
		
		MyApplication myApp = (MyApplication) getApplicationContext();
        id = myApp.getId();
		
		LinearLayout container = (LinearLayout) findViewById(R.id.myAssignmentsButtons);
		
		//Add current assignments to the menu
		JSONArray current = getCurrentAssignments();
		if(current != null){
			if(current.length() > 0){
				TextView curr =  new TextView(this);
				curr.setText("Current Assignments:");
				container.addView(curr);
			}
			
			Button[] currentBtns = new Button[current.length()];
			
			for(int i=0; i<currentBtns.length; i++){
				currentBtns[i] = new Button(this);
				String u = "not working";
				JSONObject jObject;
	        	JSONArray jArray = null;
				try {
					JSONObject json_data = current.getJSONObject(i);
					u = json_data.getString("name");
					final int assignmentId = json_data.getInt("assignmentId");
					final int probNum = json_data.getInt("currentProbNum");
					final int numProblems = json_data.getInt("numProblems");
					String[] templates = new String[numProblems];
					final String templateJSON = json_data.getString("templates");
					String problemJSON = json_data.getString("problems");
					final String problems;
					if(problemJSON.equals("")){
						//Templates must be turned into problems
						jObject = new JSONObject(templateJSON);
						jArray = jObject.getJSONArray("assignment");
						for(int j=0; j<templates.length; j++){
							templates[j] = jArray.getJSONObject(j).getString("template")+"";
						}
						problems = createProblems(templates, assignmentId);
					}else{
						System.out.println("problems in database is not null");
						problems = problemJSON;
					}
					
					currentBtns[i].setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							Intent i = new Intent(MyAssignments.this, AssignmentView.class);
							i.putExtra("userId", id);
							i.putExtra("assignmentId", assignmentId);
							i.putExtra("numProblems", numProblems);
							i.putExtra("currentProbNum", probNum);
							//i.putExtra("assignment", templateJSON);
							i.putExtra("problems", problems);
							startActivity(i);
						}
					});
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				currentBtns[i].setText("Assignment From "+u);
				container.addView(currentBtns[i]);
			}
		}else{
			TextView noAssignments = new TextView(this);
			noAssignments.setText("You have no assignments");
			TextView space = new TextView(this);
			space.setText("");
			container.addView(noAssignments);
			container.addView(space);
		}
		
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(MyAssignments.this, MainActivity.class);
				startActivity(i);
			}
		});
	}
	
	public JSONArray getCurrentAssignments(){
    	InputStream is = null;
    	String result = "";
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("userId", id+""));
    	
    	//http post
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(KEY_121);
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse response = httpclient.execute(httppost);
    		HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection: "+e);
    		return null;
    	}
    	
    	//convert response to string
    	try{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
    		StringBuilder sb = new StringBuilder();
    		String line = null;
    		while((line = reader.readLine()) != null){
    			sb.append(line + "\n");
    		}
    		is.close();
    		result = sb.toString();
    		System.out.println(result);
    	}catch(Exception e){
    		Log.e("log_tag", "Error converting result: "+e);
    		return null;
    	}
    	
    	//parse json data
    	JSONArray jArray = null;
    	try{
    		jArray = new JSONArray(result);
    	}catch(JSONException e){
    		Log.e("log_tag", "Error parsing data: "+e);
    		return null;
    	}
    	return jArray;
    }
	
	public String createProblems(String[] templates, int assignmentId){
		System.out.println("In createProblems:");
		String problems = "{\"problems\":[";
		for(int i=0; i<templates.length; i++){
			System.out.println("  "+templates[i]);
		}
		String dash = "\\";
		try {
			
			InetSocketAddress sa = new InetSocketAddress("10.0.2.2", 8880);
			InetSocketAddress sa2 = new InetSocketAddress("10.0.2.2", 8881);
			
			for(int i=0; i<templates.length; i++){
				Socket s = new Socket();
				if(templates[i].contains("x") || templates[i].contains("y")){
					s.connect(sa2, 2000);
				}else{
					s.connect(sa, 2000);
				}
				OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream());
				osw.write(templates[i]+"\n");
				osw.flush();
				ObjectInputStream isr = new ObjectInputStream(s.getInputStream());
				CSProb c = null;
				try {
					c = (CSProb) isr.readObject();
					System.out.println("c to JSON: "+c.probToJson());
					//String jsonProb = c.probToJson();
					if(i == templates.length-1){
						problems += (c.probToJson() + "]}");
					}else{
						problems += (c.probToJson() + ", ");
					}
				} catch (ClassNotFoundException e) {
					System.out.println("c cannot be created: " + e);
					e.printStackTrace();
				}
				isr.close();
			}
		} catch (IOException e1) {
			System.out.println("");
			e1.printStackTrace();
		}
		System.out.println("problems in JSON: "+problems);
		
		
		//Add the newly created problems to the database
		InputStream is = null;
    	String result = "";
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("userId", id+""));
    	nameValuePairs.add(new BasicNameValuePair("assignmentId", assignmentId+""));
    	nameValuePairs.add(new BasicNameValuePair("problems", problems+""));
    	
    	//http post
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(KEY_123);
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse response = httpclient.execute(httppost);
    		//HttpEntity entity = response.getEntity();
    		//is = entity.getContent();
    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection: "+e);
    	}
	
    	return problems;
	
	}
	
}
